import { h, toRaw } from 'vue'
import { NIcon } from 'naive-ui'
import { useIconStore } from '@/stores/iconStore'

import type { TreeOption } from 'naive-ui'

export interface Tree extends TreeOption {
    label: string
    value: string
    key: number | string
    icon?: Object
    data: any
    children?: Tree[]
}

export function toTree(data: any[] | undefined, parentColumn: string, parentValue: any, keyColumn: string, labelColumn: string, valueColumn: string): Tree[] {
    const iconStore = useIconStore()
    const res: Tree[] = []
    if (data) {
        for (let i = 0; i < data.length; i++) {
            if (data[i][parentColumn] === parentValue) {
                const temp: Tree = {
                    label: data[i][labelColumn],
                    key: data[i][keyColumn],
                    value: data[i][valueColumn],
                    data: data[i]
                }
                if (data[i].menuIcon) {
                    const iconObj = iconStore.icon(data[i].menuIcon)
                    if (iconObj) {
                        temp.icon = () => h(NIcon, null, { default: () => h(toRaw(iconObj.icon)) })
                    }
                }
                const children = toTree(data, parentColumn, data[i][keyColumn], keyColumn, labelColumn, valueColumn)
                if (children !== null && children.length > 0) {
                    temp.children = children
                }
                res.push(temp)
            }
        }
    }
    return res
}